<template>
  <div>
    <div class="request" v-if="!addShow && !dtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'ReturnApply'"
          v-hasPermi="['system:returnApply:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'ReturnReview'"
          v-hasPermi="['system:returnReview:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:returnApply:add']"
          class="btn search"
          v-if="route.name === 'ReturnApply'"
          @click="showAdd('add')"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="stockReturnCode">退库编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDate">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantName">申请人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">申请部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="stockReturnTypeName">退库类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deliveryApplyCode">关联出库单</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectName">原项目</el-checkbox>
            </div>
            <div>
              <el-checkbox label="checkStatusName">审核状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
            <div v-if="route.name === 'ReturnReview'">
              <el-checkbox label="inStatusName">退库状态</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.stockReturnCode"
            class="search-input"
            placeholder="请输入退库编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicantName"
            class="search-input"
            placeholder="请输入申请人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.deliveryApplyCode"
            class="search-input"
            placeholder="请输入出库单编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.projectName"
            class="search-input"
            placeholder="请输入项目名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.stockReturnType"
            placeholder="请选择退库类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in typeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.checkStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div
          class="search-item"
          v-if="route.name === 'ReturnReview'"
          v-hasPermi="['system:returnReview:list']"
        >
          <el-select
            v-model="params.inStatus"
            placeholder="请选择退库状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in StockStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="returnApplyList"
        border
        height="64vh"
        @sort-change="sortChange"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <!-- 操作模式 -->
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'ReturnApply' &&
                  [0, 5, 6].includes(row.checkStatus)
                "
                v-hasPermi="['system:returnApply:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ReturnApply' && [1].includes(row.checkStatus)
                "
                v-hasPermi="['system:returnApply:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
              <el-icon
                v-if="route.name === 'ReturnApply'"
                v-hasPermi="['system:returnApply:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="route.name === 'ReturnReview'"
                v-hasPermi="['system:returnReview:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ReturnReview' &&
                  [1, 2].includes(row.checkStatus) &&
                  row.auditStatus == 1
                "
                v-hasPermi="['system:returnReview:audit']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('audit', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ReturnReview' &&
                  row.checkStatus == 3 &&
                  row.inStatus == 0
                "
                v-hasPermi="['system:returnReview:check']"
                title="入库"
                color="#0000FF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <img
                  src="@/assets/icons/images/warehousing.png"
                  style="width: 16px; height: 18px"
                />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ReturnApply' &&
                  [0, 5].includes(row.checkStatus)
                "
                v-hasPermi="['system:returnApply:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'ReturnReview' &&
                  [5].includes(row.checkStatus) &&
                  false
                "
                v-hasPermi="['system:returnReview:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="退库编号"
          prop="stockReturnCode"
          v-if="checkList.includes('stockReturnCode')"
          :show-overflow-tooltip="true" sortable="custom"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDate"
          v-if="checkList.includes('applicantDate')"
          :show-overflow-tooltip="true" sortable="custom"
        />
        <el-table-column
          label="申请人"
          prop="applicantName"
          v-if="checkList.includes('applicantName')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        />
        <el-table-column
          label="申请部门"
          prop="deptName"
          v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        />
        <el-table-column
          label="退库类型"
          prop="stockReturnTypeName"
          v-if="checkList.includes('stockReturnTypeName')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        />
        <el-table-column
          label="关联出库单"
          prop="deliveryApplyCode"
          v-if="checkList.includes('deliveryApplyCode')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        >
          <template #default="{ row }">
            <span
              v-if="row.deliveryApplyId"
              @click="handleDeliveryDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.deliveryApplyCode }}</span
            >
            <span v-else>{{ row.deliveryApplyCode }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="原项目"
          prop="projectName"
          v-if="checkList.includes('projectName')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        />
        <el-table-column
          label="审核状态"
          prop="checkStatusName"
          v-if="checkList.includes('checkStatusName')"
          :show-overflow-tooltip="true" sortable="custom"
          min-width="80"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.checkStatusName)">{{
              row.checkStatusName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="下步流程"
          prop="nextNodeName" sortable="custom"
          v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="120"
        />
        <el-table-column
          v-if="
            route.name === 'ReturnReview' && checkList.includes('inStatusName')
          "
          label="退库状态" sortable="custom"
          prop="inStatusName"
          :show-overflow-tooltip="true"
          min-width="80"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 新增 -->
    <OutorderAdd
      ref="outorderAddRef"
      v-if="addShow"
      v-model:addShow="addShow"
      @refreshList="getList"
      :pageType="pageType"
    />
    <!-- 查看、审核-->
    <OutorderDtl
      ref="outorderDtlRef"
      v-if="dtlShow"
      v-model:dtlShow="dtlShow"
      @refreshList="getList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import { getDictsApi } from '@/api/dict'
import OutorderAdd from './add.vue'
import OutorderDtl from './dtl.vue'
import {
  deleteReturn,
  getReturnListApi,
  checkCancelAddDdl,
} from '@/api/stock/returnapply'
import { addTableHeaderApi, getTableHeaderApi } from '@/api/pub'
import { ElMessage, ElMessageBox } from 'element-plus'
// 路由
const route = useRoute()
const router = useRouter()
// 搜索参数
const params = reactive({
  stockReturnCode: '', // 退库申请编号
  applicantName: '', // 申请人
  deliveryApplyCode: '', //出库单编号
  projectName: '', // 项目名称
  stockReturnType: null, // 退库类型
  checkStatus: null, // 审核状态
  inStatus: null, //退库状态
  pageNum: 1,
  pageSize: 50,
  type: 0,
})
// 表格加载效果
const loading = ref(false)
// 退库列表
const returnApplyList = ref([])

// 退库类型列表
const typeList = ref([])
// 审核状态列表
const auditStatusList = ref([])
//退库状态列表
const StockStatusList = ref([])

// 总数
const total = ref(0)
// 退库新增组件引用
const outorderAddRef = ref(null)
//退库查看组件引用
const outorderDtlRef = ref(null)
// 退库新增组件显隐
const addShow = ref(false)
// 退库查看组件显隐
const dtlShow = ref(false)
// 操作类型
const pageType = ref('')

const checkList = ref([
  'stockReturnCode',
  'applicantDate',
  'deptName',
  'stockReturnTypeName',
  'deliveryApplyCode',
  'projectName',
  'checkStatusName',
  'nextNodeName',
  'inStatusName',
])

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(',')
  const result = await addTableHeaderApi({
    moduleType: route.name === 'ReturnApply' ? 30 : 31,
    titleField: str,
  })
}

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: route.name === 'ReturnApply' ? 30 : 31,
  })
  if (result.code == 200) {
    var arr = result.data.titleField.split(',')
    checkList.value = arr
  }
}

/**
 * @description: 新增
 */
const showAdd = async (type) => {
  pageType.value = type
  addShow.value = true
  nextTick(() => {
    outorderAddRef.value.showReturnAdd()
  })
}

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    stockReturnCode: '', // 退库申请编号
    applicantName: '', // 申请人
    deliveryApplyCode: '', //出库单编号
    projectName: '', // 项目名称
    stockReturnType: null, // 退库类型
    checkStatus: null, // 审核状态
    inStatus: null, //退库状态
    type: 0,
    pageNum: 1,
    pageSize: 50,
  })
  getList()
}

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getList();
};


/**
 * @description: 获取退库列表
 */
const getList = async () => {
  try {
    loading.value = true
    let { pageNum, pageSize } = params
    if (route.name === 'ReturnReview') {
      params.type = 2
    } else {
      params.type = 1
    }
    const res = await getReturnListApi({ pageNum, pageSize }, params)
    returnApplyList.value = res.rows
    total.value = res.total
    loading.value = false
  } catch {
    loading.value = false
  }
}
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据 (0:未提交,1:待审核,2:审核中,3:已通过,4:未通过,5:已撤销,6:已驳回)
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case 'edit':
      pageType.value = type
      addShow.value = true
      nextTick(() => {
        outorderAddRef.value.handleDetailInfo(row.stockReturnId)
      })
      break
    case 'revoke':
      ElMessageBox.confirm('确定撤销该数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'confirmBtnClass',
        cancelButtonClass: 'cancelBtnClass',
      })
        .then(async () => {
          const res = await checkCancelAddDdl(row.stockReturnId)
          if (res.code === 200) {
            ElMessage.success(res.msg)
            getList()
          } else {
            ElMessage.error(res.msg)
          }
        })
        .catch(() => {})
      break
    case 'detail':
      pageType.value = type
      dtlShow.value = true
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row)
      })
      break
    case 'audit':
      pageType.value = type
      dtlShow.value = true
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row)
      })
      break
    case 'check':
      pageType.value = type
      dtlShow.value = true
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row)
      })
      break
    case 'delete':
      ElMessageBox.confirm('此操作将删除该退库，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtnClass',
        cancelButtonClass: 'cancelBtnClass',
        type: 'warning',
      })
        .then(async () => {
          const res = await deleteReturn(row.stockReturnId)
          if (res.code === 200) {
            ElMessage.success(res.msg)
            getList()
          } else {
            ElMessage.error(res.msg)
          }
        })
        .catch(() => {})
      break

    default:
      break
  }
}
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum
  const pageSize = params.pageSize
  const truelndex = (currentPage - 1) * pageSize + index + 1
  return truelndex
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  //退库类型
  await getDictsApi('erp_stock_return_type').then((res) => {
    if (res.code === 200) {
      typeList.value = res.data
    }
  })
  // 审核状态
  await getDictsApi('erp_stock_return_check_status').then((res) => {
    if (res.code === 200) {
      if (route.name === 'ReturnApply') {
        auditStatusList.value = res.data
      } else {
        auditStatusList.value = res.data.filter((status) => status.value !== 0)
      }
    }
  })
  // 退库状态
  if (route.name === 'ReturnReview') {
    await getDictsApi('stock_return_status').then((res) => {
      if (res.code === 200) {
        StockStatusList.value = res.data
      }
    })
  }
}

/* 跳转出库详情 */
const handleDeliveryDetail = (row) => {
  const { href } = router.resolve({
    path: `/stock/outorder`,
    query: { deliveryApplyId: row.deliveryApplyId },
  })
  window.open(href, '_blank')
  // window.open(
  //   `/stock/outorder?deliveryApplyId=${row.deliveryApplyId}`,
  //   "_blank"
  // );
}
onMounted(() => {
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.applyId) {
    let applyId = route.query.applyId
    pageType.value = 'detail'
    dtlShow.value = true
    nextTick(() => {
      outorderDtlRef.value.handleDetailInfo({
        stockReturnId: applyId,
        checkStatus: 3,
      })
    })
  }
  console.log(99, route.query)
  if (route.query?.businessId) {
    let applyId = route.query.businessId
    if (
      route.query.checkStatus === '待审核' ||
      route.query.checkStatus === '审核中'
    ) {
      pageType.value = 'audit'
      dtlShow.value = true
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo({
          stockReturnId: Number(applyId),
          checkStatus: 1,
        })
      })
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId
    pageType.value = 'detail'
    dtlShow.value = true
    nextTick(() => {
      outorderDtlRef.value.handleDetailInfo({
        stockReturnId: Number(applyId),
        checkStatus: 3,
      })
    })
  }
  getDicts()
  getList()
  getTableHeader()
})
</script>

<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
